<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of MY_Model
 *
 * @author lucas
 */
class MY_Model extends CI_Model {

    //put your code here

    protected $table = '';
    protected $apelido = '';
    protected $salve_query = TRUE;
    private $salve_query_pesquisa = array();
    private $salve_query_primary_key = NULL;
    private $salve_query_primary_key_vakue = NULL;

    public function __construct() {
        parent::__construct();
    }

    public function set_table($table) {
        $this->table = $table;
    }

    public function set_apelido($apelido) {
        $this->apelido = $apelido;
    }

    public function set_salve_query($salve_query) {
        $this->salve_query = $salve_query;
    }

    /**
     * Consultar Acessos
     * @param array $dados
     * @return int|null
     */
    public function get($params = array()) {
        $this->sql->sql_db($params);
        $query = $this->db->get($this->table . ($this->apelido != '' ? ' as ' . $this->apelido : ''));

        if ($query->num_rows() > 0) {
            return $this->inset_log('SELECT INDIVIDUAL', $query->row());
        } else {
            return $this->inset_log('SELECT INDIVIDUAL', NULL);
        }
    }

    /**
     * Consultar Acessos
     * @param array $dados
     * @return int|null
     */
    public function consultar($params = array()) {
        $this->sql->sql_db($params);
        $query = $this->db->get($this->table . ($this->apelido != '' ? ' as ' . $this->apelido : ''));
        if ($query->num_rows() > 0) {
            return $this->inset_log('SELECT GERAL', $query->result());
        } else {
            return $this->inset_log('SELECT GERAL', NULL);
        }
    }

    /**
     * Consultar total de Acessos
     * @param array $dados
     * @return int
     */
    public function total($params = array()) {
        $this->sql->sql_db($params);
        return $this->inset_log('SELECT TOTAL', $this->db->count_all_results($this->table . ($this->apelido != '' ? ' as ' . $this->apelido : '')));
    }

    /**
     * Cadastrar Acessos
     * @param array $dados
     * @return int|null
     */
    public function cadastrar($params = array()) {
        $this->sql->sql_db($params);
        $this->db->insert($this->table);
        if ($this->db->affected_rows() > 0) {
            return $this->inset_log('INSERT', $this->db->insert_id());
        } else {
            return $this->inset_log('INSERT', NULL);
        }
    }

    /**
     * Alterar Acessos
     * @param int $id
     * @param array $dados
     * @return int|null
     */
    public function alterar($params = array()) {
        $this->inset_log_campos($params, 'pesquisa');
        $this->sql->sql_db($params);
        $this->db->update($this->table);
        if ($this->db->affected_rows() > 0) {
            return $this->inset_log('UPDATE', TRUE, $params);
        } else {
            return $this->inset_log('UPDATE', NULL, $params);
        }
    }

    /**
     * Excluir Acessos
     * @param int $id
     * @return true|null
     */
    public function excluir($params = array()) {
        $this->inset_log_campos($params, 'pesquisa');
        $this->sql->sql_db($params);
        $this->db->delete($this->table);
        if ($this->db->affected_rows() > 0) {
            return $this->inset_log('DELETE', TRUE, $params);
        } else {
            return $this->inset_log('DELETE', NULL, $params);
        }
    }

    /**
     * Debug SQL Acessos
     * @return string
     */
    public function debug() {
        pre($this->db->last_query());
    }

    private function inset_log($tipo = NULL, $retorno = NULL, $params2 = array()) {
        if ($this->session->userdata('usuario_id_user') AND $this->uri->segment(2) !== 'logs') {
            if ($this->salve_query === TRUE AND $tipo != NULL) {
                $params = array();
                $params['SET']['tipo'] = $tipo;
                $params['SET']['query'] = $this->db->last_query();
                $params['SET']['data_hora_cadastro'] = date('Y-m-d H:i:s');
                $params['SET']['id_user'] = $this->session->userdata('usuario_id_user');
                $this->sql->sql_db($params);
                $this->db->insert($this->config->item('tblLogQuerys'));
                if ($tipo == 'DELETE' OR $tipo == 'UPDATE') {
                    $this->inset_log_campos($params2, $tipo);
                }
            }
        }
        return $retorno;
    }

    private function inset_log_campos($params = array(), $tipo = 'pesquisa') {
        $campos = '*';
        $where = array();
        if (isset($params['SET'])) {
            $campos = implode(',', array_keys($params['SET']));
        }
        if (isset($params['AND'])) {
            foreach ($params['AND'] as $key => $value) {
                $where[$key] = $value;
            }
        }
        $b_consultar = $this->get(
                array(
                    'AND' => $where,
                    'CAMPOS' => $campos
                )
        );

        if ($b_consultar != NULL) {
            if ($tipo === 'pesquisa') {
                $this->salve_query_pesquisa = $b_consultar;
                $_primary_key = $this->db->field_data($this->table);
                if (count($_primary_key) > 0) {
                    foreach ($_primary_key as $key => $value) {
                        foreach ($value as $k => $v) {
                            if ($k == 'primary_key' AND $v == 1) {
                                $this->salve_query_primary_key = $value->name;
                                $this->salve_query_primary_key_vakue = $v;
                            }
                        }
                    }
                }
            } else {
                if (count($this->salve_query_pesquisa) > 0) {
                    $b_consultar = (array) $b_consultar;
                    foreach ($this->salve_query_pesquisa as $key => $value) {
                        if (isset($b_consultar[$key])) {
                            if ($this->salve_query_primary_key_vakue != NULL) {

                                if ($b_consultar[$key] != $value) {
                                    $params = array();
                                    $params['SET']['id'] = $this->salve_query_primary_key_vakue;
                                    $params['SET']['campo_id'] = $this->salve_query_primary_key;
                                    $params['SET']['campo_alterado'] = $key;
                                    $params['SET']['valor_atual'] = $value;
                                    $params['SET']['valor_novo'] = $b_consultar[$key];
                                    $params['SET']['data_hora_cadastro'] = date('Y-m-d H:i:s');
                                    $params['SET']['id_user'] = $this->session->userdata('usuario_id_user');
                                    $this->sql->sql_db($params);
                                    $this->db->insert($this->config->item('tblLogCampos'));
                                }
                            }
                        }
                    }
                }
            }
        }
        return;
    }

}
